#!/bin/bash

if [ ! -f ./remote_info.json ];then
        echo -e "\n./remote_info.json does not exist!\n"
        exit 1
fi

SOFTWARE_DEB=$(cat /etc/os-release  | grep -E "^NAME=" | awk -F '=' '{print$2}' | sed "s/[\'\"]//g" | egrep "Ubuntu|Debian" | wc -l)
SOFTWARE_YUM=$(cat /etc/os-release  | grep -E "^NAME=" | awk -F '=' '{print$2}' | sed "s/[\'\"]//g" | egrep "CentOS|Linux" | wc -l)
if [ $SOFTWARE_DEB -eq 0 ];then
        sudo apt install -y jq
elif [ $SOFTWARE_YUM -eq 0 ];then
        sudo yum install -y epel-release
        sudo yum install -y jq
fi
clear
## 定义系统名称(Define system name)
SYSTEM_NAME=$(cat /etc/os-release  | grep -E "^NAME=" | awk -F '=' '{print$2}' | sed "s/[\'\"]//g")
## 定义系统版本(Define system version)
SYSTEM_VERSION_NUMBER=$(cat /etc/os-release  | grep -E "VERSION_ID=" | awk -F '=' '{print$2}' | sed "s/[\'\"]//g")
ARCH=$(uname -m)

echo -e ''
echo -e '+---------------------------------------------------+'
# echo -e '|                                                   |'
echo -e '|        欢迎使用 SSH Remote 管理系统               |'
# echo -e '|                                                   |'
echo -e '+---------------------------------------------------+'
# echo -e '|                                                   |'
echo -e "|        运行环境: \033[34m${SYSTEM_NAME} ${SYSTEM_VERSION_NUMBER} ${SYSTEM_ARCH}\033[0m                    |"
echo -e "|        系统时间: \033[34m$(date "+%Y-%m-%d %H:%M:%S")\033[0m              |"
# echo -e '|                                                   |'
echo -e '+---------------------------------------------------+'
echo -e ''
## 远程列表(Remote List)
SERVER_TOTAL=$(grep 'remote_user' ./remote_info.json | wc -l)
for ((i=0; i<$SERVER_TOTAL; i++))
do
        REMARK=$(cat ./remote_info.json | jq -r ".[$i].remark")
        REMOTE_IP=$(cat ./remote_info.json | jq -r ".[$i].remote_ip")
        INDEX=$(($i+1))
        echo -e "\033[36m         ❖  $REMARK \t $REMOTE_IP \t $INDEX )\033[0m"
done
## 启动任务(Start mission)
CHOICE_NUM=$(echo -e "\n\033[33m└─ Please enter the number you want to remote? :  \033[0m")
read -p "${CHOICE_NUM}" INPUT
REMOTE_USER=$(cat remote_info.json | jq -r ".[$INPUT-1].remote_user")
REMOTE_IP=$(cat remote_info.json | jq -r ".[$INPUT-1].remote_ip")
REMOTE_PORT=$(cat remote_info.json | jq -r ".[$INPUT-1].remote_port")
ssh $REMOTE_USER@$REMOTE_IP -p $REMOTE_PORT